import collections
class Solution(object):
    def getAncestors(self, n, edges):
        d = collections.defaultdict(int)
        e = collections.defaultdict(set)
        ans = [set() for _ in range(n)]
        for u, v in edges:
            d[v] += 1
            e[u].add(v)
        now = set()
        for i in range(n):
            if d[i] == 0:
                now.add(i)
        while now:
            next_set = set()
            for u in now:
                for v in e[u]:
                    d[v] -= 1
                    ans[v].add(u)
                    ans[v].update(ans[u])
                    if d[v] == 0:
                        next_set.add(v)
            now = next_set
        ans = [list(item) for item in ans]
        for i in range(len(ans)):
            ans[i].sort()
        return ans

